/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.viewcontroller.setter;

import foxmob.mlts.component.FileManager;
import foxmob.mlts.model.EnglishTest;
import foxmob.mlts.model.Question;
import foxmob.mlts.model.Section;
import foxmob.mlts.model.Subsection;
import foxmob.mlts.model.TreeObject;
import foxmob.mlts.viewcontroller.student.StudentsForm;
import foxmob.mlts.viewcontroller.setter.SetterPreviewForm;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

/**
 *
 * @author Lunayo
 */
public class SetterForm extends javax.swing.JFrame {

    /**
     * Creates new form SetterForm
     */
    public SetterForm() {
        initComponents();
    }
    
    private void loadTestRecord() {
        // iterate test record 
        // to create a tree model
        DefaultMutableTreeNode root = 
            new DefaultMutableTreeNode(testRecord.getTestName());
        for (Section section : testRecord.getSections()) {
            DefaultMutableTreeNode sectionNode =
                    new DefaultMutableTreeNode(section);
            for (Subsection subsection : section.getSubsections()) {
                DefaultMutableTreeNode subsectionNode =
                    new DefaultMutableTreeNode(subsection);
                for (Question question : subsection.getQuestions()) {
                    DefaultMutableTreeNode questionNode =
                        new DefaultMutableTreeNode(question);
                    subsectionNode.add(questionNode);
                }
                sectionNode.add(subsectionNode);
            }
            root.add(sectionNode);
        }
            
        DefaultTreeModel treeModel = new DefaultTreeModel(root);
        recordTree.setModel(treeModel);
    }
    
    public TreeObject getObjectFromTree(DefaultMutableTreeNode object) {
        TreeObject treeObject = new TreeObject();
        int level = object.getLevel();
        FileManager fileManager = FileManager.getInstanceObject();
        if (level == QUESTION_LEVEL) {
            TreeNode subsectionNode = object.getParent();
            TreeNode sectionNode = subsectionNode.getParent();
            TreeNode rootNode = sectionNode.getParent();
            int questionIndex = subsectionNode.getIndex(object);
            int subsectionIndex = sectionNode.getIndex(subsectionNode);
            int sectionIndex = rootNode.getIndex(sectionNode);
            Section section = testRecord.getSections().get(sectionIndex);
            Subsection sub = section.getSubsections().get(subsectionIndex);
            Question question = sub.getQuestions().get(questionIndex);
            
            // create new tree object for passing 
            treeObject.setQuestion(question);
            treeObject.setSection(section);
            treeObject.setSubsection(sub);
            treeObject.setRecord(testRecord);
        } else if (level == SUB_SECTION_LEVEL) {
            TreeNode sectionNode = object.getParent();
            TreeNode rootNode = sectionNode.getParent();
            int subsectionIndex = sectionNode.getIndex(object);
            int sectionIndex = rootNode.getIndex(sectionNode);
            Section section = testRecord.getSections().get(sectionIndex);
            Subsection sub = section.getSubsections().get(subsectionIndex);
            
            // create new tree object for passing
            treeObject.setSection(section);
            treeObject.setSubsection(sub);
            treeObject.setRecord(testRecord);
        } else if (level == SECTION_LEVEL) {
            TreeNode rootNode = object.getParent();
            int sectionIndex = rootNode.getIndex(object);
            Section section = testRecord.getSections().get(sectionIndex);
            
            // create new tree object for passing 
            treeObject.setSection(section);
            treeObject.setRecord(testRecord);
        }
        
        return treeObject;
    }
    
    public void deleteRecord(DefaultMutableTreeNode node) {
        int level = node.getLevel();
        TreeObject treeObject = getObjectFromTree(node);
        FileManager manager = FileManager.getInstanceObject();
        if (level == QUESTION_LEVEL) {
            TreeNode subsectionNode = node.getParent();
            TreeNode sectionNode = subsectionNode.getParent();
            TreeNode rootNode = sectionNode.getParent();
            Section section =
                testRecord.getSectionWithID(treeObject.getSection().getID());
            Subsection subsection = 
                    section.getSubsectionWithID(treeObject.getSubsection().getID());
            Question question =
                    subsection.getQuestionWithID(treeObject.getQuestion().getID());
            subsection.removeQuestion(question);
        } else if (level == SUB_SECTION_LEVEL) {
            TreeNode sectionNode = node.getParent();
            TreeNode rootNode = sectionNode.getParent();
            Section section =
                testRecord.getSectionWithID(treeObject.getSection().getID());
            Subsection subsection = 
                    section.getSubsectionWithID(treeObject.getSubsection().getID());
            section.removeSubSection(subsection);
        } else if (level == SECTION_LEVEL) {
            TreeNode rootNode = node.getParent();
            Section section =
                testRecord.getSectionWithID(treeObject.getSection().getID());
            testRecord.removeSection(section);
        }
        try {
            manager.saveToFile(testRecord);
        } catch (IOException ex) {
            Logger.getLogger(SetterForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
/**
 *
 * @param notification 
 */
    public void modifyTreeDidFinish() {
        // reload the data
        loadTestRecord();
    }
    
    public void openRecordDidFinish(EnglishTest testRecord) {
        this.testRecord = testRecord;
        loadTestRecord();
    }
    
 /**
 *
 *  end of notification
 */
    
    public void invokeComponent(DefaultMutableTreeNode node, int status) {
        int level = node.getLevel();
        TreeObject treeObject = getObjectFromTree(node);
        if (status == ADD_EVENT) {
            // If event is add event
            // the component will only trigger add form
            // when the level is up one level
            level += 1;
        }
        if (level == QUESTION_LEVEL) {
            if (status != DELETE_EVENT) {
                QuestionForm questionForm = new QuestionForm();
                questionForm.setTreeObject(treeObject);
                questionForm.setCurrentState(QuestionForm.ADD_STATE);
                // update the combo box component
                questionForm.updateQuestionComponents(treeObject);
                if (status == EDIT_EVENT) {
                    // fill in the text box
                    questionForm.fillQuestionComponents(treeObject);
                    questionForm.setCurrentState(QuestionForm.EDIT_STATE);
                }
                questionForm.setDelegate(this);
                questionForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                questionForm.setVisible(true);
            }
        } else if (level == SUB_SECTION_LEVEL) {
            if (status != DELETE_EVENT) {
                SubsectionForm subsectionForm = new SubsectionForm();
                subsectionForm.setTreeObject(treeObject);
                subsectionForm.setCurrentState(QuestionForm.ADD_STATE);
                if (status == EDIT_EVENT) {
                    // fill in the text box
                    subsectionForm.fillSubsectionComponents(treeObject);
                    subsectionForm.setCurrentState(QuestionForm.EDIT_STATE);
                }
                subsectionForm.setDelegate(this);
                subsectionForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                subsectionForm.setVisible(true);
            }
        } else if (level == SECTION_LEVEL) {
            if (status != DELETE_EVENT) {
                SectionForm sectionForm = new SectionForm();
                sectionForm.setTreeObject(treeObject);
                sectionForm.setCurrentState(QuestionForm.ADD_STATE);
                if (status == EDIT_EVENT) {
                    // fill in the text box
                    sectionForm.fillSectionComponents(treeObject);
                    sectionForm.setCurrentState(QuestionForm.EDIT_STATE);
                }
                sectionForm.setDelegate(this);
                sectionForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                sectionForm.setVisible(true);
            }
        }
        
        // if delete event
        if (status == DELETE_EVENT) {
            // Confimation box
            int response = JOptionPane.showConfirmDialog(null, 
                    "Are you sure you want to delete ?"
                    + "\nAll of the children will also be deleted", 
                    "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
                deleteRecord(node);
                // notify the finish method
                modifyTreeDidFinish();
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToggleButton1 = new javax.swing.JToggleButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        setterPanel = new javax.swing.JPanel();
        navigationLabel = new javax.swing.JLabel();
        deleteButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        recordTree = new javax.swing.JTree();
        addButton = new javax.swing.JButton();
        setterMenuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        newMenuItem = new javax.swing.JMenuItem();
        openMenuItem = new javax.swing.JMenuItem();
        menuView = new javax.swing.JMenu();
        menuItemSetter = new javax.swing.JMenuItem();
        menuItemPreview = new javax.swing.JMenuItem();
        menuEdit = new javax.swing.JMenu();

        jToggleButton1.setText("jToggleButton1");

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setterPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        navigationLabel.setText("MELT Record");

        deleteButton.setText("Delete");
        deleteButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                deleteObjectListener(evt);
            }
        });

        editButton.setText("Edit");
        editButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                editObjectListener(evt);
            }
        });

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        recordTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        recordTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                recordTreenodeSelection(evt);
            }
        });
        jScrollPane1.setViewportView(recordTree);

        addButton.setText("Add");
        addButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addObjectListener(evt);
            }
        });

        org.jdesktop.layout.GroupLayout setterPanelLayout = new org.jdesktop.layout.GroupLayout(setterPanel);
        setterPanel.setLayout(setterPanelLayout);
        setterPanelLayout.setHorizontalGroup(
            setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, setterPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(navigationLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                    .add(jScrollPane1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, editButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, deleteButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(addButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        setterPanelLayout.setVerticalGroup(
            setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(setterPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(navigationLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(setterPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(setterPanelLayout.createSequentialGroup()
                        .add(addButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(editButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(deleteButton))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 307, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        fileMenu.setText("File");

        newMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        newMenuItem.setText("New record...");
        newMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(newMenuItem);

        openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        openMenuItem.setText("Open record...");
        openMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(openMenuItem);

        setterMenuBar.add(fileMenu);

        menuView.setText("View");
        menuView.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuViewActionPerformed(evt);
            }
        });

        menuItemSetter.setText("Setter");
        menuView.add(menuItemSetter);

        menuItemPreview.setText("Preview");
        menuItemPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemPreviewActionPerformed(evt);
            }
        });
        menuView.add(menuItemPreview);

        setterMenuBar.add(menuView);

        menuEdit.setText("Edit");
        setterMenuBar.add(menuEdit);

        setJMenuBar(setterMenuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(setterPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(setterPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void recordTreenodeSelection(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_recordTreenodeSelection
        // TODO add your handling code here:
        
    }//GEN-LAST:event_recordTreenodeSelection

    private void editObjectListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_editObjectListener
        // TODO add your handling code here:
        DefaultMutableTreeNode node = 
                (DefaultMutableTreeNode)recordTree.getLastSelectedPathComponent();
        invokeComponent(node, EDIT_EVENT);
    }//GEN-LAST:event_editObjectListener

    private void deleteObjectListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_deleteObjectListener
        // TODO add your handling code here:
        DefaultMutableTreeNode node = 
                (DefaultMutableTreeNode)recordTree.getLastSelectedPathComponent();
        invokeComponent(node, DELETE_EVENT);
        
    }//GEN-LAST:event_deleteObjectListener

    private void menuItemPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemPreviewActionPerformed
        // TODO add your handling code here:
        /*FileManager fileManager = FileManager
         * .getInstanceObject();
        ArrayList<EnglishTest> records = fileManager.getTestRecord();
        StudentsForm studentForm = 
                new StudentsForm(testRecord.getSections().get(0), 0);
        studentForm.setVisible(true);/*
        * 
        */
       System.out.println("action perform");
       this.setVisible(false);
       // SetterPreviewForm form1 = new SetterPreviewForm();
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SetterPreviewFormFrame().setVisible(true);
            }
        });
        
    }//GEN-LAST:event_menuItemPreviewActionPerformed

    private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuItemActionPerformed
        // TODO add your handling code here:
        OpenTestRecordForm recordForm = new OpenTestRecordForm();
        recordForm.setDelegate(this);
        recordForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        recordForm.setVisible(true);
    }//GEN-LAST:event_openMenuItemActionPerformed

    private void newMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newMenuItemActionPerformed
        // TODO add your handling code here:
        NewTestRecordForm recordForm = new NewTestRecordForm();
        recordForm.setCurrentState(ADD_EVENT);
        recordForm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        recordForm.setVisible(true);
    }//GEN-LAST:event_newMenuItemActionPerformed

    private void addObjectListener(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addObjectListener
        // TODO add your handling code here:
        DefaultMutableTreeNode node =
         (DefaultMutableTreeNode)recordTree.getLastSelectedPathComponent();
        invokeComponent(node, ADD_EVENT);

    }//GEN-LAST:event_addObjectListener

    private void menuViewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuViewActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_menuViewActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SetterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SetterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SetterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SetterForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SetterForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JMenu menuEdit;
    private javax.swing.JMenuItem menuItemPreview;
    private javax.swing.JMenuItem menuItemSetter;
    private javax.swing.JMenu menuView;
    private javax.swing.JLabel navigationLabel;
    private javax.swing.JMenuItem newMenuItem;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JTree recordTree;
    private javax.swing.JMenuBar setterMenuBar;
    private javax.swing.JPanel setterPanel;
    // End of variables declaration//GEN-END:variables

    private EnglishTest testRecord;
    
    public static final int TEST_RECORD_LEVEL = 0;
    public static final int SECTION_LEVEL = 1;
    public static final int SUB_SECTION_LEVEL = 2;
    public static final int QUESTION_LEVEL = 3;
    public static final int ADD_EVENT = 0;
    public static final int EDIT_EVENT = 1;
    public static final int DELETE_EVENT = 2;
}
